/********************************************************************************
 * Project Name		[JavaEE_Web]
 * File Name     	[StudentServlet.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package mvc.controller;

import java.io.IOException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.dao.IStudentDao;
import mvc.dao.StudentCriteria;
import mvc.dao.factory.StudentDaoFactory;
import mvc.domain.Student;

/**
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
@WebServlet(name = "StudentServlet", urlPatterns = "*.do")
public class StudentServlet extends HttpServlet {

	private static final long serialVersionUID = 3708011660157717866L;

	private IStudentDao studentDao = StudentDaoFactory.getInstance().getStudentDao();

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 获得ServletPath, 例如/edit.do
		String servletPath = request.getServletPath();
		// 截取字符串获得方法名
		String methodName = servletPath.substring(servletPath.lastIndexOf('/') + 1, servletPath.lastIndexOf('.'));

		try {
			// 利用反射获取methodName对应的方法
			Method method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class,
					HttpServletResponse.class);
			// 利用反射调用对应的方法
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询所有记录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void queryAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String studentName = request.getParameter("name");
		String studentGender = request.getParameter("gender");

		List<Student> students = null;

		if (studentName == "" && studentGender == "") {
			// 查询结果
			students = studentDao.findAllStudents();
		} else {
			Student student = new Student();
			if (studentName != "")
				student.setName(studentName);
			if (studentGender != "")
				student.setGender(studentGender);

			StudentCriteria criteria = new StudentCriteria(student);
			students = studentDao.findStudentsByCriteria(criteria);
		}
		// 将结果放入到request中
		request.setAttribute("students", students);
		// 转发页面到index.jsp
		request.getRequestDispatcher("/jsp_mvc/index.jsp").forward(request, response);
	}

	/**
	 * 保存记录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void save(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// 获取表单参数
		String name = request.getParameter("name");
		String age = request.getParameter("age");
		String gender = request.getParameter("gender");
		String birthday = request.getParameter("birthday");

		// 检验name是否被占用
		int count = studentDao.getStudentCountByName(name);
		if (count > 0) {
			// 用户名被占用, 提示错误信息
			String errorMessage = "用户名" + name + "已存在";
			request.setAttribute("errorMessage", errorMessage);
			request.getRequestDispatcher("/jsp_mvc/add.jsp").forward(request, response);
			return;
		}

		// 通过验证, 把表单封装为一个Student对象
		try {
			Student student = new Student();
			student.setName(name);
			student.setAge(Integer.parseInt(age));
			student.setGender(gender);
			student.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));

			// 保存对象
			studentDao.save(student);
		} catch (NumberFormatException | ParseException e) {
			e.printStackTrace();
		}

		// 重定向到首页, 避免重复提交的问题
		response.sendRedirect("queryAll.do");
	}

	/**
	 * 转到编辑页面
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String forwardPath = "/jsp_mvc/error.jsp";

		try {
			String id = request.getParameter("id");
			Student student = studentDao.findStudentById(Integer.parseInt(id));
			request.setAttribute("student", student);
			forwardPath = "/jsp_mvc/edit.jsp";
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		request.getRequestDispatcher(forwardPath).forward(request, response);
	}

	/**
	 * 更新记录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取表单参数
		String id = request.getParameter("id");
		String oldName = request.getParameter("oldName");
		String newName = request.getParameter("name");
		String age = request.getParameter("age");
		String gender = request.getParameter("gender");
		String birthday = request.getParameter("birthday");

		// 检查名称是否被占用
		// 比较oldName和newName是否相同
		// Step 1: 相同说明newName可用[name未修改, oldName和newName值一样]
		// Step 2: 不同则调用Dao方法校验[name修改, oldName和newName值不一样]
		if (!oldName.equalsIgnoreCase(newName)) {
			int count = studentDao.getStudentCountByName(newName);
			if (count > 0) {
				// 用户名被占用, 提示错误信息
				String errorMessage = "用户名" + newName + "已存在";
				request.setAttribute("errorMessage", errorMessage);
				request.getRequestDispatcher("/jsp_mvc/edit.jsp").forward(request, response);
				return;
			}
		}

		// 通过验证, 把表单封装为一个Student对象
		try {
			Student student = new Student();
			student.setId(Integer.parseInt(id));
			student.setName(newName);
			student.setAge(Integer.parseInt(age));
			student.setGender(gender);
			student.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));

			// 修改记录
			studentDao.update(student);
		} catch (NumberFormatException | ParseException e) {
			e.printStackTrace();
		}

		// 重定向到首页, 避免重复提交的问题
		response.sendRedirect("queryAll.do");
	}

	/**
	 * 删除记录
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String id = request.getParameter("id");
			studentDao.delete(Integer.parseInt(id));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}

		request.getRequestDispatcher("queryAll.do").forward(request, response);
	}
}
